package com.example.my_bookkeeping.ui.account;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.my_bookkeeping.R;
import com.example.my_bookkeeping.data.manager.Manager;
import com.example.my_bookkeeping.data.manager.UserManager;
import com.example.my_bookkeeping.data.user.User;

import java.util.ArrayList;

public class AccountFragment extends Fragment implements Manager.Observer {
    private UserSpinnerAdapter spinnerAdapter;
    private UserManager userManager;
    private TextView tvAccountName, tvAccountCategory, tvAccountBalance;

    @Override
    public void update() {
        updateAccountInfo(userManager.getCurrentUser());
        if (spinnerAdapter != null) {
            spinnerAdapter.clear();
            spinnerAdapter.addAll(userManager.getAll());
            spinnerAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        userManager.removeObserver(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_account, container, false);

        // 初始化 UserDataStore
        userManager = UserManager.getInstance();
        userManager.addObserver(this);

        // 获取 Spinner 实例，设置数据
        Spinner userSpinner = rootView.findViewById(R.id.spinner_account);
        spinnerAdapter = new UserSpinnerAdapter(userManager.getAll());
        userSpinner.setAdapter(spinnerAdapter);

        // 初始化控件
        tvAccountName = rootView.findViewById(R.id.tv_account_name);
        tvAccountCategory = rootView.findViewById(R.id.tv_account_category);
        tvAccountBalance = rootView.findViewById(R.id.tv_account_balance);

        // 监听账户选择事件
        userSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                User selectedUser = userManager.getAll().get(position);
                updateAccountInfo(selectedUser);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 处理未选择情况
            }
        });

        // 初始化账户信息
        if (!userManager.getAll().isEmpty()) {
            updateAccountInfo(userManager.getAll().get(0));
        }

        // 处理用户添加
        Button button_account_AddAccount = rootView.findViewById(R.id.btn_add_account);
        button_account_AddAccount.setOnClickListener(v -> showUserInfoEditDialog(null));

        // 处理账户修改
        Button button_account_EditAccount = rootView.findViewById(R.id.btn_edit_account);
        button_account_EditAccount.setOnClickListener(v -> showUserInfoEditDialog(userManager.getCurrentUser()));

        // 处理账户删除
        Button button_account_DeleteAccount = rootView.findViewById(R.id.btn_delete_account);
        button_account_DeleteAccount.setOnClickListener(v -> {
            // 加载对话框布局
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("删除账户")
                    .setMessage("确认删除该账户吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 从数据库中删除账户
                        userManager.delete(userManager.getCurrentUser());
                        if (userManager.getAll().isEmpty()) {
                            userManager.reset();
                            update();
                        }
                        // 更新 Spinner 数据
                        userManager.switchUser(userManager.getAll().get(0));
                        userSpinner.setSelection(0);
                    })
                    .setNegativeButton("取消", null);

            // 显示对话框
            AlertDialog dialog = builder.create();
            dialog.show();
        });
        return rootView;
    }

    private void showUserInfoEditDialog(@Nullable User editUser) {
        // 加载对话框布局
        LayoutInflater dialogInflater = LayoutInflater.from(requireContext());
        View dialogView = dialogInflater.inflate(R.layout.dialog_add_account, null);

        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        String title = editUser == null ? "编辑账户" : "添加账户";
        builder.setTitle(title)
                .setView(dialogView)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss());

        // 显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();

        setupEditText(dialogView, editUser);

        Button button_confirm = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        button_confirm.setOnClickListener(v1 -> {
            // 处理用户输入
            EditText editText_accountName = dialogView.findViewById(R.id.et_username);
            EditText editText_accountType = dialogView.findViewById(R.id.et_user_type);
            EditText editText_accountBalance = dialogView.findViewById(R.id.et_user_balance);
            String accountName = editText_accountName.getText().toString();
            String accountType = editText_accountType.getText().toString();
            String accountBalance = editText_accountBalance.getText().toString();
            if (accountName.isEmpty()) {
                editText_accountName.setError(getString(R.string.account_warning_user_name_empty));
                return;
            }
            if (accountBalance.isEmpty()) {
                editText_accountBalance.setError(getString(R.string.account_warning_user_amount_invalid));
                return;
            }

            double amount = Math.round(Double.parseDouble(accountBalance) * 100) / 100.0;
            if (editUser != null)
                userManager.update(accountName, accountType, amount);
            else
                userManager.add(new User(accountName, accountType, amount));
            dialog.dismiss();
        });
    }

    private void setupEditText(View dialogView, User user) {
        if (user != null) {
            // 将用户信息填入对话框, 并设置光标位置到末尾
            EditText editText_accountName = dialogView.findViewById(R.id.et_username);
            EditText editText_accountType = dialogView.findViewById(R.id.et_user_type);
            EditText editText_accountBalance = dialogView.findViewById(R.id.et_user_balance);

            editText_accountName.setText(user.getName());
            editText_accountName.setSelection(editText_accountName.getText().length());
            editText_accountType.setText(user.getRemark());
            editText_accountType.setSelection(editText_accountType.getText().length());
            editText_accountBalance.setText(String.valueOf(user.getAmount()));
            editText_accountBalance.setSelection(editText_accountBalance.getText().length());
        }
    }

    private void updateAccountInfo(User user) {
        if (user != null) {
            tvAccountName.setText(user.getName());
            tvAccountCategory.setText(user.getRemark());
            tvAccountBalance.setText(String.valueOf(user.getAmount()));
            userManager.switchUser(user);
        }
    }

    private class UserSpinnerAdapter extends ArrayAdapter<User> {
        public UserSpinnerAdapter(ArrayList<User> users) {
            super(requireContext(), android.R.layout.simple_spinner_item, users);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            return initView(position, convertView, parent);
        }

        @Override
        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            return initView(position, convertView, parent);
        }

        private View initView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
            }
            TextView textView = convertView.findViewById(android.R.id.text1);
            User user = getItem(position);
            if (user != null) {
                textView.setText(user.getName());
            }
            return convertView;
        }
    }
}